//
//  CollectionTableViewController.m
//  LWB_Project
//
//  Created by lanou3g on 15/11/19.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//

#import "CollectionTableViewController.h"
#import "FirstNewsTableViewCell.h"
#import "SecondNewsTableViewCell.h"
#import "NewsDetailTableViewController.h"
#import "AnimationTool.h"
#import "DataBasehandle.h"
@interface CollectionTableViewController ()
{
    BOOL _editStyle;
}
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong ) NSMutableArray *dataArray;
@end

@implementation CollectionTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    //收藏在数据库中！
    
    [[DataBasehandle sharedDataBasehandle] createtableName:@"NewsCollectionSave" Modelclass:[NewsModels class]];
    self.dataArray = [[DataBasehandle sharedDataBasehandle] selectAllModel];
    
    [self.tableView reloadData];
    
    //设置编辑状态为可以编辑做准备
    
    [self.tableView setEditing:YES];
    _editStyle = UITableViewCellEditingStyleDelete;
    [self.tableView setEditing:NO];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35 + 100 * [UIScreen mainScreen].bounds.size.width/320;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NewsModels *model = self.dataArray[indexPath.row];  
    if ([model.skipType isEqualToString:@"photoset"])
    {
        
        //修正bug补丁
        
        if((model.imgextra1 == nil)  && (model.imgextra2 == nil))
        {
            FirstNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstNewsTableViewCell" ];
            if (cell == nil)
            {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"FirstNewsTableViewCell" owner:self options:nil] firstObject];
            }
            [cell setModel:model];
            
            cell.selectedBackgroundView = [[UIView alloc] init];
            return cell;
        }else
        {
            
            SecondNewsTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondNewsTableViewCell" ];
            if (cell == nil)
            {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"SecondNewsTableViewCell" owner:self options:nil] firstObject];
            }
            
            [cell setModel:model];
            cell.selectedBackgroundView = [[UIView alloc] init];
            
            return cell;
        }
        
        
    }else
    {
        FirstNewsTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstNewsTableViewCell" ];
        if (cell == nil)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FirstNewsTableViewCell" owner:self options:nil] firstObject];
        }
        [cell setModel:model];
        cell.selectedBackgroundView = [[UIView alloc] init];
        return cell;
    }
}
#pragma mark--- 跳到下个界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        
        //如果有网络
        NSString *NetStates = [[NSUserDefaults standardUserDefaults] objectForKey:@"NETStates"];
        if ([NetStates isEqualToString:@"YES"])
        {
            NewsDetailTableViewController *vc = [[NewsDetailTableViewController alloc] init];
            vc.model = self.dataArray[indexPath.row];
            
            
            [self.navigationController.view.layer addAnimation:[AnimationTool addAnimationWithAnimationSubType:kCATransitionFromRight withType:@"rippleEffect" duration:1.0f] forKey:nil];
            [self.navigationController pushViewController:vc animated:YES];
        }else
        {
            
            [self checkNetalerView];
        }
    }
  

-(void)checkNetalerView
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
    [alertView show];
}


// 第三步：设置哪个cell 可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 都可以编辑
    return YES;
}

// 第四步：在进入编辑之前，通过这个方法 返回编辑的状态（插入还是删除）
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return _editStyle;
}

// 第五步：真正的执行编辑的事情
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 处理删除或插入的过程
    // 判断 是要做插入 还是 要做 删除
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        

        //在数据库中移除model 根据index.row
        [[DataBasehandle sharedDataBasehandle] createtableName:@"NewsCollectionSave" Modelclass:[NewsModels class]];
        [[DataBasehandle sharedDataBasehandle] deleteFromTableModel:self.dataArray[indexPath.row]];
        
        // 在编辑的时候，一定要先处理数据源 然后再处理view
        [self.dataArray removeObjectAtIndex:indexPath.row];
        
        // tableView 删除一个cell的方法 第一个参数代表 删除哪个分区喜下的cell, 第二个参数 代表 删除的动画
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
